import React, { useEffect, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, Form, message, Space, Table } from 'antd'
import { EditFormInline } from '@/components/CustomForm'
import { useFormBase } from './useForm'
import { useForm } from 'antd/es/form/Form'
import { getProductClassConfigByType, getProductFabricPageList, productFabricConfigEdit } from '@/api/goods'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './detail.less'
import { useAppSelector } from '@/store/hooks'
import { STATUSCONFIRMTEXT } from '@/constant'
import PermissionButton from '@/components/PermissionButton'
import { ITableData } from './types'
import useSearchSupplier from '@/hooks/useSearchSupplier'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [FormStylebaseinfo] = useForm()
  const [ispedding, setispedding] = useState<boolean>(false)
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [detailInfo, setDetail] = useState<Record<string, any>>({})
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [desInfoList, setDesInfoList] = useState<IDesListType>([
    { label: '面料编码', key: 'fabricCode', content: '-' },
    { label: '开发季', key: 'devSeason', content: '-' },
    { label: '关联面种编码', key: 'fabricTypeCode', content: '-' },
    { label: '面料名称', key: 'fabricName', content: '-' },
    { label: '可用大类', key: 'classNames', content: '-' },
    { label: '面料季节', key: 'seasonClassify', content: '-' },
    { label: '面料定位', key: 'devLocation', content: '-' },
    { label: '面料价格带', key: 'priceTag', content: '-' },
    {
      label: '是否集约',
      key: 'intensiveStatus',
      content: '-',
      format: (rows) => STATUSCONFIRMTEXT[rows?.intensiveStatus] || '-',
    },
    { label: '供应商', key: 'supplierNames', content: '-' },
    { label: '面料成本', key: 'cost', content: '-' },
    { label: '面料备注', key: 'remark', content: '-' },
  ])
  //基础信息
  const [isbaseinfoEdit, setisbaseinfoEdit] = useState<boolean>(false)
  const { SupplierOption, handleSearchSupplier, setSupplierOption } = useSearchSupplier('supplierId')
  const [query] = useSearchParams()
  const fabricId = query.get('fabricId')
  useEffect(() => {
    if (fabricId) {
      getProductClassConfig()
      getDetail()
    }
  }, [])
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const getDetail = async () => {
    const res = await getProductFabricPageList<ITableData>({ fabricId })
    if (res.code === 200) {
      const details = res?.data?.list[0]
      setDetail(details)
      handleDetailFactory(desInfoList, details, setDesInfoList)
    }
  }
  const startEdit = async (
    setisEdit: React.Dispatch<React.SetStateAction<boolean>>,
    callback: (data?: any) => Promise<any>,
  ) => {
    setispedding(true)
    const res = await callback().finally(() => setispedding(false))
    if (res.code === 200) {
      setisEdit(false)
      message.open({
        type: 'success',
        content: '操作成功',
        duration: 5,
      })
      // getDetail()
      navigate(-1)
    }
  }
  const handleDetailFactory = (
    sourceList: IDesListType,
    targetInfo: any,
    set: React.Dispatch<React.SetStateAction<IDesListType>>,
  ) => {
    const res = sourceList?.map((item) => {
      if (typeof item.format === 'function') {
        return {
          ...item,
          content: item.format(targetInfo),
        }
      } else {
        return {
          ...item,
          content: targetInfo[item.key + ''] || '-',
        }
      }
    })
    set(res)
  }

  return (
    <DetailContainer className="goods_fabric_detail_page">
      <Descriptions
        title="基础信息"
        list={isbaseinfoEdit ? [] : desInfoList}
        extra={
          <Space>
            <PermissionButton
              permission="editFabricBase"
              loading={ispedding}
              type="primary"
              onClick={async () => {
                if (isbaseinfoEdit) {
                  const data = await FormStylebaseinfo.validateFields()
                  const paramsData = {
                    ...data,
                    fabricId,
                  }
                  startEdit(setisbaseinfoEdit, () => productFabricConfigEdit(paramsData))
                } else {
                  setisbaseinfoEdit(true)
                  FormStylebaseinfo.setFieldsValue({
                    ...detailInfo,
                  })
                }
              }}
            >
              {isbaseinfoEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {isbaseinfoEdit ? (
              <Button
                onClick={() => {
                  setisbaseinfoEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormInline
          className="sep_forminline_style"
          editConfig={useFormBase({
            detailInfo,
            classBig,
            DICTDATA,
            SupplierOption,
            handleSearchSupplier,
          })}
          form={FormStylebaseinfo}
        />
      </Descriptions>
    </DetailContainer>
  )
}
export default Index
